package com.book.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.book.common.Result;
import com.book.dto.BookQueryRequest;
import com.book.entity.Book;
import com.book.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/book")
@CrossOrigin
public class BookController {
    
    @Autowired
    private BookService bookService;
    
    /**
     * 分页查询图书
     */
    @PostMapping("/page")
    public Result<IPage<Book>> getBookPage(@RequestBody BookQueryRequest request) {
        IPage<Book> page = bookService.getBookPage(request);
        return Result.success(page);
    }
    
    /**
     * 根据ID查询图书
     */
    @GetMapping("/{id}")
    public Result<Book> getBookById(@PathVariable Long id) {
        Book book = bookService.getById(id);
        return Result.success(book);
    }
    
    /**
     * 新增图书
     */
    @PostMapping
    public Result<?> addBook(@RequestBody Book book) {
        book.setCreateTime(LocalDateTime.now());
        book.setUpdateTime(LocalDateTime.now());
        bookService.save(book);
        return Result.success();
    }
    
    /**
     * 更新图书
     */
    @PutMapping
    public Result<?> updateBook(@RequestBody Book book) {
        book.setUpdateTime(LocalDateTime.now());
        bookService.updateById(book);
        return Result.success();
    }
    
    /**
     * 删除图书
     */
    @DeleteMapping("/{id}")
    public Result<?> deleteBook(@PathVariable Long id) {
        bookService.removeById(id);
        return Result.success();
    }
    
    /**
     * 获取图书类别统计
     */
    @GetMapping("/statistics/category")
    public Result<List<Map<String, Object>>> getCategoryStatistics() {
        List<Map<String, Object>> statistics = bookService.getCategoryStatistics();
        return Result.success(statistics);
    }
    
    /**
     * 获取价格区间统计
     */
    @GetMapping("/statistics/price-range")
    public Result<List<Map<String, Object>>> getPriceRangeStatistics() {
        List<Map<String, Object>> statistics = bookService.getPriceRangeStatistics();
        return Result.success(statistics);
    }
} 